Rotate Image

You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up: Could you do this in-place?

题目大意:顺时针旋转方阵,要求空间复杂度为O(1)

题目难度:Medium

/**
 * Created by gzdaijie on 16/5/23
 * 先转置,再左右交换即可
 */
public class Solution {
    public void rotate(int[][] matrix) {
        if (matrix == null || matrix.length == 0) return;

        int len = matrix.length;
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j < len; j++) {
                swap(matrix, i, j, j, i);
            }
        }

        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len/2; j++) {
                swap(matrix, i, j, i, len - j - 1);
            }
        }
    }

    private void swap(int[][] matrix, int x1, int y1, int x2, int y2) {
        int tmp = matrix[x1][y1];
        matrix[x1][y1] = matrix[x2][y2];
        matrix[x2][y2] = tmp;
    }
}
gzdaijie            updated 2016-05-23 23:00:34

results matching ""

    No results matching ""